package cn.schoolwow.quickdao.test.module.business.user.dml.userRole.flow.edit;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.database.parent.DatabaseType;
import cn.schoolwow.quickdao.test.entity.Role;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickdao.test.entity.UserRole;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.junit.Assert;

public class EditUserRoleFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        checkDatabase(flowContext);
        setUpdateValue(flowContext);
        updateUser(flowContext);
        updateRole(flowContext);
    }

    @Override
    public String name() {
        return "更新用户角色表";
    }

    private void checkDatabase(FlowContext flowContext){
        DatabaseType databaseType = flowContext.checkInstanceData(DatabaseType.class);

        switch (databaseType){
            case SQLite:{
                flowContext.broken("SQLite数据库不支持update语句进行表连接操作");
            }break;
        }
    }

    private void setUpdateValue(FlowContext flowContext){
        User insertUser = (User) flowContext.checkData("insertUser");
        Role insertRole = (Role) flowContext.checkData("insertRole");

        insertUser.setUsername("超级管理员");
        insertRole.setRoleName("超级管理员");
    }

    private void updateUser(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        User insertUser = (User) flowContext.checkData("insertUser");
        Role insertRole = (Role) flowContext.checkData("insertRole");

        int effect = dao.query(User.class)
                .joinTable(UserRole.class, "id", "userId")
                .addQuery("roleId", insertRole.getId())
                .done()
                .addUpdate("username", insertUser.getUsername())
                .addNullUpdate("extraData")
                .execute()
                .update();
        Assert.assertEquals(1, effect);
    }

    private void updateRole(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        User insertUser = (User) flowContext.checkData("insertUser");
        Role insertRole = (Role) flowContext.checkData("insertRole");

        int effect = dao.query(Role.class)
                .joinTable(UserRole.class, "id", "roleId")
                .addQuery("userId", insertUser.getId())
                .done()
                .addUpdate("roleName", insertRole.getRoleName())
                .execute()
                .update();
        Assert.assertEquals(1, effect);
    }

}
